#!/bin/sh
IFS="
"
VIP=$1
NAME=$2

log()
{
	echo "$@" >&2
}

usage()
{
	log
	log "Usage: $0 <filename.vip> <Package-Name.pkg>" >&2
	log " Creates a WvAutoInstall package in directory Package-Name.pkg,"
	log " including the Versa installer and the given .vip package to"
	log " install."
	log
	exit 1
}

find_top()
{
	cd $(dirname $(which "$0"))
	log "$0 is in '$PWD'" >&2
	if [ -e versabox.tmp/bin/versapack ]; then
		echo "$PWD/versabox.tmp"
	else
		cd ..
		echo "$PWD"
	fi
}

TOP=$(find_top)
log "versabox top is '$TOP'" >&2

export PATH=$TOP/bin:$PATH


if [ -z "$VIP" -o -z "$NAME" ]; then
	usage
fi

if [ ! -e "$VIP" ]; then
	log "$VIP: no such file!"
	exit 2
fi

if [ ! -f "$VIP" ]; then
	log "$VIP: not a normal file."
	exit 2
fi

if ! unzip -qq -t $VIP vip.ini; then
	log "$VIP: contains no vip.ini!"
	exit 2
fi

if [ -e "$NAME" -a ! -d "$NAME" ]; then
	log "$NAME: already exists!"
	exit 3
fi

if [ -e "$NAME" ]; then
	log "Deleting '$NAME'."
	rm -rf "$NAME"
fi

if [ ! -e $TOP/versabox.tar.gz ]; then
	log "Generating $TOP/versabox.tar.gz."
	if ! $TOP/bin/versa-repack-self; then
		log "Can't generate versabox.tar.gz!"
		exit 4
	fi
fi

log "Creating '$NAME'."
mkdir $NAME
ln $VIP $NAME/
cp $TOP/versabox.tar.gz $NAME/0.tgz
cp $TOP/versa-proc.sh $TOP/versa-pre.ini $TOP/versa-post.ini $NAME/
MINV=$(unzip -qq -p $VIP vip.ini | grep -i '^Min Weaver Version' | head -n 1)
FULLNAME=$(unzip -qq -p $VIP vip.ini | grep -i '^Name = ' | head -n 1 | sed 's/^Name = //')

if [ -z "$MINV" ]; then
	MINV="Min Weaver Version = 4.32"
fi
if [ -z "$FULLNAME" ]; then
	FULLNAME="$NAME"
fi
cat >$NAME/wvauto.ini <<-EOF
	[WvAutoInstall]
	$MINV
	Default Package = $NAME
	
	[WvAutoInstall Packages]
	$NAME = $FULLNAME
	
	[$NAME]
	versa-pre.ini = ini
	versa-post.ini = ini2
	0.tgz = extract versa-installer-0
	$VIP = copy versa-installer-0
EOF

echo "Done."
exit 0
